﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using bus_TienichNPC;
using BaocaoNPC.common;
using Microsoft.Windows.Controls;

namespace BaocaoNPC.Usercontrols
{
    /// <summary>
    /// Interaction logic for THONGTINKHACHHANG_DUYET.xaml
    /// </summary>
    public partial class THONGTINKHACHHANG_DUYET : UserControl
    {
        #region Khai báo
        public String strMadviqly = NPCUS_DanhMuc.Pglobal.strMa_dviqly != "" && NPCUS_DanhMuc.Pglobal.strMa_dviqly != null ? NPCUS_DanhMuc.Pglobal.strMa_dviqly : "PA";
        public String strTen_dviqly = NPCUS_DanhMuc.Pglobal.strTen_dviqly != "" && NPCUS_DanhMuc.Pglobal.strTen_dviqly != null ? NPCUS_DanhMuc.Pglobal.strTen_dviqly : "cty..";
        DataSet ds_KH = new BCNPCEntities.EXCEL.ds_CN();
        DataSet dsResult = new DataSet();
        CN_THEODOINO_bus THEODOINO_bus = new CN_THEODOINO_bus();
        //Thay doi thong tin Khach hang SMS - TUNGVT
        #endregion

        public THONGTINKHACHHANG_DUYET()
        {
            InitializeComponent();            
            DataSet ds_TNV = GlobalServices.Service_NPCUS.SELECT_TNGAN_THONGTIN_KHANG(strMadviqly);
            Load_TV(ds_TNV);
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            dtpNgaytao.SelectedDate = DateTime.Now;
        }

        private void Load_TV(DataSet data)
        {
            try
            {
                if (data.Tables[0].Rows.Count == 0 || data == null) return;
                TreeViewItem superNode = new TreeViewItem();
                TreeViewItem _node = new TreeViewItem();
                TreeViewItem _childnode = new TreeViewItem();
                CheckBox chkNode = new CheckBox();
                CheckBox chkChildNode = new CheckBox();

                if (tvTNV != null) tvTNV.Items.Clear();
                DataView dv = new DataView(data.Tables[0]);
                dv.Sort = "MA_TNGAN";
                if (dv.Count == 0)
                {
                    superNode.Header = "Không có dữ liệu TNV";
                    superNode.Tag = "Không có dữ liệu TNV@";
                    tvTNV.Items.Add(superNode);
                    return;
                }
                CheckBox chkSuperNode = new CheckBox();
                chkSuperNode.Content = strTen_dviqly;
                chkSuperNode.Tag = "NUTGOC" + "@" + "" + "@" + "" + "@" + "" + "@" + "";
                chkSuperNode.ToolTip = strTen_dviqly;
                chkSuperNode.IsChecked = false;
                chkSuperNode.Click += new RoutedEventHandler(this.CheckBox_Click);
                superNode = new TreeViewItem();
                superNode.Header = chkSuperNode;
                superNode.IsExpanded = true;
                //tvTNV.Items.Add(superNode);
                string strnutcha = "";
                string strNutCon = "";
                string str_thungan = "";
                string str_ma_thungan = "";
                foreach (DataRowView dr in dv)
                {
                    str_ma_thungan = dr["MA_TNGAN"].ToString();
                    str_thungan = dr["TEN_TNGAN"].ToString();
                    #region "parentnode"
                    if (str_thungan != strnutcha)
                    {
                        chkNode = new CheckBox();
                        chkNode.Content = str_thungan;
                        chkNode.Tag = str_ma_thungan + "@NUTCHA" + "@" + "" + "@" + "" + "@" + "";
                        chkNode.ToolTip = str_thungan;
                        chkNode.IsChecked = false;
                        chkNode.Click += new RoutedEventHandler(this.CheckBox_Click);
                        _node = new TreeViewItem();
                        _node.Header = chkNode;
                        _node.IsExpanded = false;
                        tvTNV.Items.Add(_node);
                        strnutcha = str_thungan;
                        #region SoBBG
                        //if (IN != 1)
                        //{
                        //    DataSet dsBBG = new DataSet();
                        //    dsBBG = CHAMNO_OFFLINE_bus.DS_BBG(str_ma_thungan, strMadviqly);
                        //    if (dsBBG != null && dsBBG.Tables[0].Rows.Count > 0)
                        //    {
                        //        if (dsBBG.Tables.Count > 0 && dsBBG.Tables[0].Rows.Count > 0)
                        //        {
                        //            TreeViewItem superNodeBB = new TreeViewItem();
                        //            TreeViewItem _nodeBB = new TreeViewItem();
                        //            //TreeViewItem _childnodeBB = new TreeViewItem();
                        //            //CheckBox chkNodeBB = new CheckBox();
                        //            CheckBox chkChildNodeBB = new CheckBox();

                        //            // filter_treeDataSet();
                        //            //this._node.Items.Clear(); // xoa tree trước khi đỗ dữ liệu mới
                        //            DataView dv2 = new DataView(dsBBG.Tables[0]);
                        //            dv2.Sort = "SO_BBGIAO, MA_SOGCS";
                        //            string strnutcha2 = "";
                        //            string str_bienban2 = "";
                        //            string str_ma_sogcs = "";
                        //            foreach (DataRowView dr2 in dv2)
                        //            {
                        //                str_bienban2 = dr2["SO_BBGIAO"].ToString();
                        //                str_ma_sogcs = dr2["MA_SOGCS"].ToString();
                        //                //str_ma_sogcs = dr2["MA_SOGCS"].ToString();
                        //                if (IN != 1)
                        //                {
                        //                    #region "parentnode2"
                        //                    if (str_bienban2 != strnutcha2)
                        //                    {
                        //                        CheckBox chkNodeBB = new CheckBox();
                        //                        chkNodeBB.Content = str_bienban2;
                        //                        chkNodeBB.Tag = str_bienban2 + "@" + str_ma_thungan + "@" + "Biên bản" + "@NUTCHA2" + "@" + "";
                        //                        chkNodeBB.ToolTip = str_bienban2;
                        //                        chkNodeBB.IsChecked = false;
                        //                        chkNodeBB.Click += new RoutedEventHandler(this.CheckBox_Click);
                        //                        _nodeBB = new TreeViewItem();
                        //                        _nodeBB.Header = chkNodeBB;
                        //                        _nodeBB.IsExpanded = false;
                        //                        _node.Items.Add(_nodeBB);
                        //                        strnutcha2 = str_bienban2;


                        //                    }
                        //                    # endregion
                        //                    #region Ma So GCS

                        //                    TreeViewItem _nodeSo = new TreeViewItem();
                        //                    CheckBox chkChildNodeSo = new CheckBox();
                        //                    if (str_ma_sogcs != strNutCon)
                        //                    {
                        //                        CheckBox chkNodeSo = new CheckBox();
                        //                        chkNodeSo.Content = str_ma_sogcs;
                        //                        chkNodeSo.Tag = str_ma_sogcs + "@" + str_bienban2 + "@" + str_ma_thungan + "@" + "Sổ" + "@NUTCON";
                        //                        chkNodeSo.ToolTip = str_ma_sogcs;
                        //                        chkNodeSo.IsChecked = false;
                        //                        chkNodeSo.Click += new RoutedEventHandler(this.CheckBox_Click);
                        //                        _nodeSo = new TreeViewItem();
                        //                        _nodeSo.Header = chkNodeSo;
                        //                        _nodeSo.IsExpanded = false;
                        //                        _nodeBB.Items.Add(_nodeSo);
                        //                        strNutCon = str_ma_sogcs;
                        //                    }
                        //                    #endregion
                        //                }
                        //            }
                        //        }
                        //    }
                        //}
                        #endregion
                    }
                    # endregion
                }
            }
            catch (Exception ex)
            {
                return;
            }
        }

        public void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                CheckBox chk = (CheckBox)sender;
                this.Cursor = Cursors.Wait;
                TreeViewItem itemselect = tvTNV.SelectedItem as TreeViewItem;
                string[] m = chk.Tag.ToString().Split('@');
                if (chk.IsChecked == true)
                {
                    foreach (TreeViewItem supernode in tvTNV.Items)
                    {
                        checkList(supernode, chk);
                    }
                    foreach (TreeViewItem supernode in tvTNV.Items)
                    {
                        RefreshCheckBoxList(supernode);
                    }
                    if (m[1].ToString() == "NUTCHA")
                    {
                        #region NUTCHA
                        dsResult = GlobalServices.Service_NPCUS.SELECT_THONGTIN_KHANG_CHODUYET_TNGAN(strMadviqly, m[0]);                        
                        if (dsResult != null && dsResult.Tables[0].Rows.Count > 0)
                        {
                            if (ds_KH.Tables["KHACH_HANG"].Rows.Count == 0)
                            {
                                copy_dataTable(dsResult.Tables[0], ds_KH.Tables["KHACH_HANG"], m[0]);
                                ds_KH.Tables["KHACH_HANG"].DefaultView.RowFilter = "1 = 1";
                            }
                            else
                            {
                                for (int i = ds_KH.Tables["KHACH_HANG"].Rows.Count - 1; i >= 0; i--)
                                {
                                    if (ds_KH.Tables["KHACH_HANG"].Rows[i]["MA_KHANG"].ToString() == m[0].ToString())
                                    {
                                        ds_KH.Tables["KHACH_HANG"].Rows[i].Delete();
                                    }
                                }
                                ds_KH.AcceptChanges();
                                copy_dataTable(dsResult.Tables[0], ds_KH.Tables["KHACH_HANG"], m[0]);
                                ds_KH.Tables["KHACH_HANG"].DefaultView.RowFilter = "1=1";
                            }
                            grdKhachhang.ItemsSource = ds_KH.Tables["KHACH_HANG"].DefaultView;
                        }
                        #endregion
                    }
                }
                else
                {
                    #region Uncheck
                    foreach (TreeViewItem supernode in tvTNV.Items)
                    {
                        UncheckList(supernode, chk);
                    }
                    foreach (TreeViewItem supernode in tvTNV.Items)
                    {
                        RefreshCheckBoxList(supernode);
                    }
                    if (m[1].ToString() == "NUTCHA")
                    {
                        for (int i = ds_KH.Tables["KHACH_HANG"].Rows.Count - 1; i >= 0; i--)
                        {
                            if (ds_KH.Tables["KHACH_HANG"].Rows[i]["MA_TNGAN"].ToString() == m[0].ToString())
                            {
                                ds_KH.Tables["KHACH_HANG"].Rows[i].Delete();
                            }
                        } //end of for loop     

                        ds_KH.AcceptChanges();
                        ds_KH.Tables["KHACH_HANG"].DefaultView.RowFilter = "1=1";
                    }
                    #endregion
                }
                this.Cursor = Cursors.Arrow;
            }
            catch (Exception ex)
            { }
        }

        private void CHECK_KHANG_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.Cursor = Cursors.Wait;
                CheckBox chk = (CheckBox)sender;
                DataRowView drv = grdKhachhang.SelectedItem as DataRowView;
                string MA_KHANG = drv.Row["MA_KHANG"].ToString();
                if (chk.IsChecked == true)
                {

                }
                else
                {

                }
            }
            catch (Exception ex)
            { }
        }

        private void checkList(TreeViewItem nodes, CheckBox chk)
        {

            if ((CheckBox)nodes.Header == chk)
            {
                CheckAllChildsWhenParentCheck(nodes);
                return;
            }
            foreach (TreeViewItem node in nodes.Items)
            {
                if (node.Header == chk)
                {
                    if (node.Items.Count > 0)
                    {

                        foreach (TreeViewItem subNode in node.Items)
                        {
                            //check all Node
                            CheckBox chkNode = (CheckBox)subNode.Header;
                            chkNode.IsChecked = true;
                            if (subNode.Items.Count > 0)
                            {
                                checkList(subNode, chkNode); //chk);
                            }
                        }
                        CheckParentWhenAllChildChecked(nodes);
                    }
                    else
                    {

                        CheckParentWhenAllChildChecked(nodes);
                    }
                }
                else
                {
                    checkList(node, chk);
                }

            }
        }

        private void UncheckList(TreeViewItem nodes, CheckBox chk)
        {
            if ((CheckBox)nodes.Header == chk)
            {
                UnCheckAllChildsWhenParentUnCheck(nodes);
                return;
            }
            foreach (TreeViewItem node in nodes.Items)
            {
                if (node.Header == chk)
                {
                    UnCheckParent(node);
                    if (node.Items.Count > 0)
                    {
                        foreach (TreeViewItem subNode in node.Items)
                        {
                            //check all Node
                            CheckBox chkNode = (CheckBox)subNode.Header;
                            chkNode.IsChecked = false;
                            if (subNode.Items.Count > 0)
                            {
                                UncheckList(subNode, chkNode);
                            }
                        }
                    }
                    else
                    {
                        CheckBox chkNode = (CheckBox)node.Header;
                        chkNode.IsChecked = false;
                    }
                }
                else
                {
                    UncheckList(node, chk);
                }

            }
        }

        private void UnCheckParent(TreeViewItem node)
        {
            TreeViewItem parentNode = node.Parent as TreeViewItem;
            if (parentNode != null)
            {
                CheckBox chkParentNode = (CheckBox)parentNode.Header;
                chkParentNode.IsChecked = false;
                UnCheckParent(parentNode);
            }
        }

        private void CheckParentWhenAllChildChecked(TreeViewItem nodes)
        {
            int count = 0;
            foreach (TreeViewItem node in nodes.Items)
            {
                CheckBox chkNode = (CheckBox)node.Header;
                if (chkNode.IsChecked == false)
                {
                    count = count + 1;
                    break;
                }
            }
            if (count == 0)
            {
                CheckBox chkNode = (CheckBox)nodes.Header;
                chkNode.IsChecked = true;
                TreeViewItem parentNode = nodes.Parent as TreeViewItem;
                if (parentNode != null)
                {

                    CheckParentWhenAllChildChecked(parentNode);
                }
            }
        }

        private void CheckAllChildsWhenParentCheck(TreeViewItem nodes)
        {
            foreach (TreeViewItem node in nodes.Items)
            {
                CheckBox chkNode = (CheckBox)node.Header;
                chkNode.IsChecked = true;
                CheckAllChildsWhenParentCheck(node);
            }
        }

        private void UnCheckAllChildsWhenParentUnCheck(TreeViewItem nodes)
        {
            foreach (TreeViewItem node in nodes.Items)
            {
                CheckBox chkNode = (CheckBox)node.Header;
                chkNode.IsChecked = false;
                UnCheckAllChildsWhenParentUnCheck(node);
            }
        }

        private void RefreshCheckBoxList(TreeViewItem nodes)
        {
            DataRow[] dr = null;
            foreach (TreeViewItem subNode in nodes.Items)
            {
                CheckBox chkNode = (CheckBox)subNode.Header;
                if (subNode.Items.Count > 0)
                {
                    RefreshCheckBoxList(subNode);
                }
            }
        }

        private void copy_dataTable(DataTable dtnguon, DataTable dtDich, string ma_tngan)
        {
            try
            {
                DataRow[] rgINS = dtnguon.Select();
                for (int i = 0; i < rgINS.Length; i++)
                {
                    DataRow dr = dtDich.NewRow();
                    dr["MA_KHANG"] = rgINS[i]["MA_KHANG"];
                    dr["TEN_KHANG"] = rgINS[i]["TEN_KHANG"];
                    dr["DIA_CHI"] = rgINS[i]["DIA_CHI"];
                    dr["SDT"] = rgINS[i]["SDT"];
                    dr["WEBSITE"] = rgINS[i]["WEBSITE"];
                    dr["EMAIL"] = rgINS[i]["EMAIL"];
                    dr["NGAY_SINH"] = rgINS[i]["NGAY_SINH"];
                    dr["FAX"] = rgINS[i]["FAX"];
                    dr["SO_CMT"] = rgINS[i]["SO_CMT"];
                    dr["NGAY_CAP"] = rgINS[i]["NGAY_CAP"];
                    dr["NOI_CAP"] = rgINS[i]["NOI_CAP"];
                    dr["MA_TNGAN"] = rgINS[i]["MA_TNGAN"];
                    dr["NGAY_TAO"] = rgINS[i]["NGAY_TAO"];
                    dr["TRANG_THAI"] = rgINS[i]["TRANG_THAI"];
                    if (rgINS[i]["TRANG_THAI"].ToString() == "True") dr["STATUS"] = "Duyệt";
                    else dr["STATUS"] = "Chưa duyệt";
                    dtDich.Rows.Add(dr);
                    dtDich.AcceptChanges();
                }
            }
            catch (Exception ex)
            { }
        }

        private void txtTimkiem_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Enter)
                {
                    if (txtTimkiem.Text != "")
                    {
                        dsResult = GlobalServices.Service_NPCUS.SEARCH_THONGTIN_KHANG(txtTimkiem.Text, dtpNgaytao.SelectedDate.Value);
                        dsResult.Tables[0].DefaultView.RowFilter = "1 = 1";
                        grdKhachhang.ItemsSource = dsResult.Tables[0].DefaultView;
                    }
                    else
                    {
                        ds_KH.Tables["KHACH_HANG"].DefaultView.RowFilter = "1 = 1";
                        grdKhachhang.ItemsSource = ds_KH.Tables["KHACH_HANG"].DefaultView;
                    }
                }
            }
            catch (Exception ex)
            { }
        }

        private void btnCapnhat_Click(object sender, RoutedEventArgs e)
        {
            string error="";
            for (int i = 0; i < grdKhachhang.Items.Count; i++)
            {
                DataGridRow row = (DataGridRow)grdKhachhang.ItemContainerGenerator.ContainerFromIndex(i);
                CheckBox chk = grdKhachhang.Columns[0].GetCellContent(row) as CheckBox;
                TextBlock MA_KHANG = grdKhachhang.Columns[1].GetCellContent(row) as TextBlock;
                TextBlock TRANG_THAI = grdKhachhang.Columns[2].GetCellContent(row) as TextBlock;
                TextBlock TENKHANG = grdKhachhang.Columns[3].GetCellContent(row) as TextBlock;
                TextBlock DIACHI = grdKhachhang.Columns[4].GetCellContent(row) as TextBlock;
                TextBlock CMT = grdKhachhang.Columns[5].GetCellContent(row) as TextBlock;
                TextBlock SDT = grdKhachhang.Columns[6].GetCellContent(row) as TextBlock;
                TextBlock WEBSITE = grdKhachhang.Columns[7].GetCellContent(row) as TextBlock;
                TextBlock EMAIL = grdKhachhang.Columns[8].GetCellContent(row) as TextBlock;
                TextBlock NGAYSINH = grdKhachhang.Columns[9].GetCellContent(row) as TextBlock;
                TextBlock FAX = grdKhachhang.Columns[10].GetCellContent(row) as TextBlock;
                TextBlock NGAYCAP = grdKhachhang.Columns[11].GetCellContent(row) as TextBlock;
                TextBlock NOICAP = grdKhachhang.Columns[12].GetCellContent(row) as TextBlock;

                if (chk.IsChecked == true)
                {
                    if (TRANG_THAI.Text == "Chưa duyệt")
                    {
                        GlobalServices.Service_NPCUS.UPDATE_TRANGTHAI_KHACHHANG(strMadviqly, MA_KHANG.Text, DIACHI.Text, SDT.Text,
                            WEBSITE.Text, EMAIL.Text, Convert.ToDateTime(NGAYSINH.Text), FAX.Text, CMT.Text, Convert.ToDateTime(NGAYCAP.Text),
                            NOICAP.Text, "True", TENKHANG.Text);
                        GlobalServices.Service_NPCUS.update_NPC_SUBS_SMS_sql(MA_KHANG.Text, SDT.Text, ref error);
                    }
                }
                else
                {
                    if (TRANG_THAI.Text == "Duyệt")
                        GlobalServices.Service_NPCUS.UPDATE_STATUS_KHACHHANG(strMadviqly, MA_KHANG.Text, DIACHI.Text, SDT.Text,
                                WEBSITE.Text, EMAIL.Text, Convert.ToDateTime(NGAYSINH.Text), FAX.Text, CMT.Text, Convert.ToDateTime(NGAYCAP.Text),
                                NOICAP.Text, "False", TENKHANG.Text);
                }
            }
        }

        private void btnChontat_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < grdKhachhang.Items.Count; i++)
            {
                DataGridRow row = (DataGridRow)grdKhachhang.ItemContainerGenerator.ContainerFromIndex(i);
                CheckBox chk = grdKhachhang.Columns[0].GetCellContent(row) as CheckBox;
                if (chk.IsChecked == false)
                {
                    chk.IsChecked = true;
                }
            }
        }

        private void btnDaochon_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < grdKhachhang.Items.Count; i++)
            {
                DataGridRow row = (DataGridRow)grdKhachhang.ItemContainerGenerator.ContainerFromIndex(i);
                CheckBox chk = grdKhachhang.Columns[0].GetCellContent(row) as CheckBox;
                if (chk.IsChecked == false)
                {
                    chk.IsChecked = true;
                }
                else chk.IsChecked = false;
            }
        }
    }
}
